//
//  CDPullDownLoadView.m
//  CuriosityDaily3
//
//  Created by JSY on 16/9/26.
//  Copyright © 2016年 theBestTeam. All rights reserved.
//

#import "CDPullDownLoadView.h"

@interface CDPullDownLoadView ()
@property (nonatomic,weak) UIImageView *starView;
@property (nonatomic,assign) BOOL *isAnimating;
@end
@implementation CDPullDownLoadView

- (instancetype)init
{
    self = [super initWithFrame:CGRectMake(0, 0, CDScreen.size.width, 100)];
    if (self) {
        [self setupUI];
    }
    return self;
}

-(void)setupUI{
    self.isAnimating = NO;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"reveal_refresh_foreground"]];
    
    [self addSubview:imageView];
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.height.offset(100);
        make.bottom.offset(0);
    }];
    
    UIImageView *starView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"reveal_refresh_sun"]];
    starView.frame = CGRectMake(145, 100, 25, 25);
    [self addSubview:starView];
    self.starView = starView;
}

-(void)scrollViewScroll:(UIScrollView *)scrollView{
    CGFloat Y = scrollView.contentOffset.y;
    /*
        75 - 0
        50
     */
    if (Y <= -100) {
    self.frame = CGRectMake(0, 0, CDScreen.size.width, 100+ABS(100+Y));
        if (self.starView.frame.origin.y > 1) {
            self.starView.frame = CGRectMake(145, 75 + (100 + Y) * 2, 25, 25);
        }else{
//            self.starView.frame = CGRectMake(145, 1, 25, 25);
//            NSLog(@"%f",Y);
            if (self.isAnimating) {
                return;
            }else{
                [self addAnimat];
//                scrollView.contentInset
            }
        }
        [scrollView layoutIfNeeded];
        [self layoutIfNeeded];
    }
    /*
     25 25
     */
    if (Y < -50 & Y > -100) {
        self.starView.frame = CGRectMake(145, 100 + (Y+50)*.5 , 25, 25);
        [self layoutIfNeeded];
    }
}

-(void)addAnimat{
    CABasicAnimation *animation = [ CABasicAnimation
                                   animationWithKeyPath: @"transform" ];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    
    //围绕Z轴旋转，垂直与屏幕
    animation.toValue = [ NSValue valueWithCATransform3D:
                         
                         CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0) ];
    animation.duration = 0.5;
    //旋转效果累计，先转180度，接着再旋转180度，从而实现360旋转
    animation.cumulative = YES;
    animation.repeatCount = 1000;
    
    [self.starView.layer addAnimation:animation forKey:nil];
    self.isAnimating = YES;
}
@end
